package com.ak.jddemo.test;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;

/**
 * @author: ak
 * @date: 2021/4/21 10:08
 * @description:
 */
@Slf4j
public class SeckillUtils {
    //分段大小
    public static Integer subSize = 50;

    public static void checkTime() throws IOException, ParseException, InterruptedException {
        //预热抢购时间
        long prepareTime = 1000 * 20;
        JSONObject headers = new JSONObject();
        headers.put(Config.headerAgent, Config.getHeaderAgentArgPhone());
        headers.put(Config.Referer, Config.RefererArg);
        headers.put("Cookie", SeckillService2.COOKIE);
        JSONObject shopDetail = JSONObject.parseObject(HttpUrlConnectionUtil.doGet("https://item-soa.jd.com/getWareBusiness?skuId=" + Config.pid, headers));
        if (shopDetail.get("yuyueInfo") != null) {
            log.info("抢购预约商品");
            //先预约商品
            String orderUrl = "https:" + JSONObject.parseObject(shopDetail.get("yuyueInfo").toString()).get("url").toString();
            log.info("预约商品");
            HttpUrlConnectionUtil.doGet(orderUrl, headers);
            String buyDate = JSONObject.parseObject(shopDetail.get("yuyueInfo").toString()).get("buyTime").toString();
            String startDate = buyDate.split("-202")[0] + ":00";
            long startTime = HttpUrlConnectionUtil.dateToTime(startDate);
            seckill(prepareTime, headers, startTime);
        } else if (shopDetail.get("miaoshaInfo") != null) {
            log.info("抢购秒杀商品");
            long startTime = Long.parseLong(JSONObject.parseObject(shopDetail.get("miaoshaInfo").toString()).get("startTime").toString());
            seckill(prepareTime, headers, startTime);
        }
    }

    private static void seckill(long prepareTime, JSONObject headers, long startTime) throws IOException, InterruptedException {
        long now = System.currentTimeMillis();
        //睡眠总时长
        long sleepTime = startTime - System.currentTimeMillis() - prepareTime;
        long subSleepTime;
        //如果是抢购前20秒，进入循环
        while (startTime > now && startTime - now > prepareTime) {
            subSleepTime = sleepTime / subSize;
            String time = HttpUrlConnectionUtil.getGapTime(startTime - System.currentTimeMillis());
            log.info("距离抢购开始还有{},等待抢购时间", time);
            log.info("分段睡眠{}秒", subSleepTime / 1000);
            Thread.sleep(subSleepTime);
            now = System.currentTimeMillis();
        }
        prepareSeckill(startTime, headers);
    }

    public static void prepareSeckill(long startTime, JSONObject headers) throws IOException, InterruptedException {
        if (Config.seckillMode) {
            try {
                log.info("进入抢购预热...重新获取抢购连接");
                SeckillService2.preparation(SeckillService2.getOrderInfoHeader());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        //进入抢购预热
        while (true) {
            //获取京东时间
            JSONObject jdTime = JSONObject.parseObject(HttpUrlConnectionUtil.doGet("https://api.m.jd.com/client.action?functionId=queryMaterialProducts&client=wh5", headers));
            long serverTime = Long.parseLong(jdTime.get("currentTime2").toString());
            if (startTime >= serverTime) {
                double time = (startTime - serverTime) / 1000d;
                if (time <= 0) {
                    break;
                }
                System.out.println("准备抢购,剩余" + time + "秒");
                Thread.sleep(200);
            } else {
                break;
            }
        }
    }

    public static void addCar() throws IOException {
        initProxyList();
        JSONObject headers = new JSONObject();
        headers.put(Config.headerAgent, Config.getHeaderAgentArgPhone());
        headers.put(Config.Referer, Config.RefererArg);
        headers.put("Cookie", SeckillService2.COOKIE);
        //加入购物车
        log.info("添加购物车");
        String s = HttpUrlConnectionUtil.doGet("https://cart.jd.com/gate.action?pcount=1&ptype=1&pid=" + Config.pid, headers);
    }

    private static void initProxyList(){
        try {
            Config.ipPool = HttpUrlConnectionUtil.ips();
            if (Config.ipPool.get(0).contains(":")) {
                log.info("ip代理池初始化成功");
            }else {
                Config.ipPool.remove(0);
                Config.ipPool.add("127.0.0.1:8080");
            }
        } catch (IOException e) {
            log.info("ip代理池初始化失败");
        }
    }
}
